package LinkList;

public class _41设计链表_双链表 {
    public  static void main(String[] args) {
        MyLinkedList ll = new MyLinkedList();
        ll.addAtIndex(0,1);
        ll.addAtIndex(0,2);
        ll.addAtIndex(2,3);
//        ll.deleteAtIndex(2);
        for (int i = 0; i < ll.size; i++) {
            System.out.println(ll.get(i));
        }
    }

    static class MyLinkedList {
        private ListNode dummyhead;
        private ListNode dummytail;
        private int size = 0;

        public MyLinkedList() {
            dummyhead = new ListNode(0,null,null);
            dummytail = new ListNode(0, dummyhead, null);
            dummyhead.next = dummytail;
            size = 0;
        }

        public int get(int index) {
            if(index >= size){
                return -1;
            }
            ListNode cur = dummyhead;
            for (int i = 0; i <= index; i++) {
                cur = cur.next;
            }
            return cur.val;

        }

        public void addAtHead(int val) {
            addAtIndex(0, val);

        }

        public void addAtTail(int val) {
            addAtIndex(size, val);

        }

        public void addAtIndex(int index, int val) {
            if (index > size) {
                return;
            }
            index = Math.max(index, 0);
            size++;

            ListNode cur = dummyhead;
            for (int i = 0; i < index; i++) {
                cur = cur.next;
            }
            ListNode newnode = new ListNode(val,cur,cur.next);
            cur.next = newnode;
            newnode.next.pred = newnode;

        }

        public void deleteAtIndex(int index) {
            if(index >= size || index < 0){
                return;
            }
            size--;

            ListNode pred = dummyhead;
            for (int i = 0; i < index; i++) {
                pred = pred.next;
            }
            pred.next = pred.next.next;
        }

        class ListNode {
            int val;
            ListNode pred, next;

            public ListNode(int val) {
                this.val = val;
            }

            public ListNode(int val, ListNode pred, ListNode next) {
                this.val = val;
                this.pred = pred;
                this.next = next;
            }
        }
    }


}
